//
//  LZAssetHandler.m
//  LZSpamCode
//
//  Created by ZengLiZhi on 2024/6/26.
//

#import "LZChangeAsset.h"
#import "LZSpamCodeManager.h"
#import "LZStringRandom.h"
#import "LZFileManager.h"

@implementation LZChangeAsset

+ (void)start{
    @autoreleasepool {
        [self handleXcassetsFiles:[LZSpamCodeManager shareInstance].gSourceCodeDir];
    }
    printf("修改 Xcassets 中的图片名称完成\n");
    [self changeAssetsMD5];
}

#pragma mark - 修改 assets 中的图片文件的MD5
+ (void)changeAssetsMD5{
    
    NSLog(@"开始修改assets图片MD5\n");
    
    NSString *assetsPath = [LZFileManager findDirectoryPath:[LZSpamCodeManager shareInstance].gSourceCodeDir targetName:@"Assets.xcassets"];
    
    // 创建一个NSTask来执行外部命令
    NSTask *task = [[NSTask alloc] init];

    // 设置任务的launch path为Python可执行文件的路径
    task.launchPath = [NSString stringWithFormat:@"%@/python3/bin/python3",[LZSpamCodeManager shareInstance].gThisProjectPath]; // 确保这是Python的正确路径

    NSString *md5Path = [NSString stringWithFormat:@"%@/ImageMD5.py",[LZSpamCodeManager shareInstance].gThisProjectPath];
    // 创建一个包含Python文件路径和参数的数组
    NSArray *arguments = @[md5Path,@"--path",assetsPath]; // 替换为你的Python文件的实际路径

    // 设置任务的arguments属性
    task.arguments = arguments;

    NSPipe *outputPipe = [NSPipe pipe];
    [task setStandardOutput:outputPipe];
    [task setStandardError:outputPipe];
    
    [task launch];//启动task
//    [task waitUntilExit];
    

    NSFileHandle *readHandle = [outputPipe fileHandleForReading];

    NSData *outputData = [readHandle readDataToEndOfFile];

    NSString *outputString = [[NSString alloc] initWithData:outputData encoding:NSUTF8StringEncoding];

    NSLog(@"%@\n",outputString);
    
    task.terminationHandler = ^(NSTask *task2){
        // 获取任务的退出状态
        int status = [task2 terminationStatus];

        // 处理任务结束
        NSLog(@"修改MD5：%@\n",status?@"完成":@"失败");
    };

}

#pragma mark - 处理 Xcassets 中的图片文件
+ (void)handleXcassetsFiles:(NSString *)directory {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray<NSString *> *files = [fm contentsOfDirectoryAtPath:directory error:nil];
    BOOL isDirectory;
    for (NSString *fileName in files) {
        NSString *filePath = [directory stringByAppendingPathComponent:fileName];
        if ([fm fileExistsAtPath:filePath isDirectory:&isDirectory] && isDirectory) {
            [self handleXcassetsFiles:filePath];
            continue;
        }
        if (![fileName isEqualToString:@"Contents.json"]) continue;
        NSString *contentsDirectoryName = filePath.stringByDeletingLastPathComponent.lastPathComponent;
        if (![contentsDirectoryName hasSuffix:@".imageset"]) continue;
        
        NSString *fileContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        if (!fileContent) continue;
        
        NSMutableArray<NSString *> *processedImageFileNameArray = @[].mutableCopy;
        static NSString * const regexStr = @"\"filename\" *: *\"(.*)?\"";
        NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionUseUnicodeWordBoundaries error:nil];
        NSArray<NSTextCheckingResult *> *matches = [expression matchesInString:fileContent options:0 range:NSMakeRange(0, fileContent.length)];
        while (matches.count > 0) {
            NSInteger i = 0;
            NSString *imageFileName = nil;
            do {
                if (i >= matches.count) {
                    i = -1;
                    break;
                }
                imageFileName = [fileContent substringWithRange:[matches[i] rangeAtIndex:1]];
                i++;
            } while ([processedImageFileNameArray containsObject:imageFileName]);
            if (i < 0) break;
            
            NSString *imageFilePath = [filePath.stringByDeletingLastPathComponent stringByAppendingPathComponent:imageFileName];
            if ([fm fileExistsAtPath:imageFilePath]) {
                NSString *newImageFileName = [[LZStringRandom randomStringWithLength:10] stringByAppendingPathExtension:imageFileName.pathExtension];
                NSString *newImageFilePath = [filePath.stringByDeletingLastPathComponent stringByAppendingPathComponent:newImageFileName];
                while ([fm fileExistsAtPath:newImageFileName]) {
                    newImageFileName = [[LZStringRandom randomStringWithLength:10] stringByAppendingPathExtension:imageFileName.pathExtension];
                    newImageFilePath = [filePath.stringByDeletingLastPathComponent stringByAppendingPathComponent:newImageFileName];
                }
                
                [LZFileManager renameFile:imageFilePath newPath:newImageFilePath];
                
                fileContent = [fileContent stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"\"%@\"", imageFileName]
                                                                     withString:[NSString stringWithFormat:@"\"%@\"", newImageFileName]];
                [fileContent writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
                
                [processedImageFileNameArray addObject:newImageFileName];
            } else {
                [processedImageFileNameArray addObject:imageFileName];
            }
            
            matches = [expression matchesInString:fileContent options:0 range:NSMakeRange(0, fileContent.length)];
        }
    }
}
@end
